package com.hqizcc.ltcs.hqbsltcs.service;

import com.hqizcc.ltcs.hqbsltcs.common.Global;
import com.hqizcc.ltcs.hqbsltcs.mapper.GetProvinceMapper;
import com.hqizcc.ltcs.hqbsltcs.model.Province;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
public class GetProvinceServiceImpl implements GetProvinceService {

    @Autowired
    private GetProvinceMapper getProvinceMapper;

    @Override
    public boolean GetProvince() {

        String url  = Global.URL;

        try {
            Element body = Jsoup.connect(url).ignoreContentType(true).timeout(600000).get().body();

            Elements elements = body.select(".provincetr td");

            Province p = new Province();

            for (Element element : elements){

                p.setProvinceName(element.select("td a").text());

                p.setProvinceName(new String(p.getProvinceName().getBytes(), "utf-8"));

                p.setProvinceHtml(element.select("td a").attr("href"));

                p.setProvinceId(p.getProvinceHtml().substring(0, p.getProvinceHtml().indexOf(".")));

                System.out.println(p.getProvinceId() + " " + p.getProvinceName() + " " + p.getProvinceHtml());

                System.out.println("插入数据库");

                getProvinceMapper.saveProvinceToDb(p.getProvinceId(), p.getProvinceName(), url + p.getProvinceHtml());
            }

        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }

        return true;
    }
}
